package com.jrx.anytxn.transaction.job.interestFile.step;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.config.InterestFileConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class InterFileListener implements JobExecutionListener {
    private static final Logger logger = LoggerFactory.getLogger(InterFileListener.class);

    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private InterestFileConfig interestFileConfig;

    @Override
    public void beforeJob(JobExecution jobExecution) {
        String reportingPath = interestFileConfig.getInterestFilePath();
        String fileName = interestFileConfig.getInterestFileName();

        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
        String toDay = DateUtils.format(org.getToday(),"yyyyMMdd");

        String collectionFileName = TransBizConstant.FILE_NAME_INTER+ "_" + toDay + "_" + fileName + ".txt";

        String filePath = reportingPath + org.getTenantId() + File.separator + toDay + File.separator;

        Path reportingFile = Paths.get(filePath + collectionFileName);
        Path pFile = Paths.get(filePath);
        if (reportingFile.toFile().exists()) {
            try {
                Files.delete(reportingFile);
            } catch (IOException e) {
                //因为listener实现的原接口未对异常做处理，所以不能抛出普通异常。
                throw new RuntimeException(e);
            }
        }

        if (!Files.exists(reportingFile)) {
            //判断文件夹是否存在
            if (!Files.isDirectory(pFile)) {
                //创建文件夹
                try {
                    Files.createDirectories(pFile);
                } catch (IOException e) {
                    logger.error("创建目录失败",e);
                }
            }
            //创建文件
            try {
                Files.createFile(reportingFile);
            } catch (IOException e) {
                logger.error("创建文件失败",e);
            }
        }
    }

    @Override
    public void afterJob(JobExecution jobExecution) {

    }
}
